/**
 * Copyright (C) 2007 The AsyncMail Group <asyncmail@googlegroups.com>
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *         http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.googlecode.asyncmail.smtpserver.mina.handler;

import java.util.Collection;

import org.apache.commons.logging.Log;
import org.springframework.beans.factory.annotation.Required;

import com.googlecode.asyncmail.common.MailAddress;
import com.googlecode.asyncmail.common.MailEnvelope;
import com.googlecode.asyncmail.smtpserver.SMTPSession;
import com.googlecode.asyncmail.smtpserver.hook.HookResult;
import com.googlecode.asyncmail.smtpserver.hook.HookReturnCode;
import com.googlecode.asyncmail.smtpserver.hook.RcptHook;
import com.googlecode.asyncmail.smtpserver.mina.SMTPSessionImpl;
import com.googlecode.asyncmail.smtpserver.mina.filter.TarpitFilter;

/**
 * Add tarpit support to SMTPServer. See
 * http://www.palomine.net/qmail/tarpit.html for more information
 * 
 */
public class TarpitHandler implements RcptHook {

    private int tarpitRcptCount = 0;

    private Log logger;

    private TarpitFilter tFilter = new TarpitFilter(true);

    @Required
    public void setLogger(Log logger) {
        this.logger = logger;
    }

    /**
     * Set the tarpit count after which the tarpit sleep time will be activated
     * 
     * @param tarpitRcptCount
     */
    public void setTarpitRcptCount(int tarpitRcptCount) {
        if (tarpitRcptCount == 0) {
            throw new IllegalArgumentException(
                    "Please set the tarpitRcptCount bigger values as 0");
        }
        this.tarpitRcptCount = tarpitRcptCount;
    }

    /**
     * Set the tarpit sleep time
     * 
     * @param tarpitSleepTime
     *                Time in milliseconds
     */
    public void setTarpitSleepTime(long tarpitSleepTime) {
        tFilter.setTarpitTime(tarpitSleepTime);
    }

    /**
     * @see com.googlecode.asyncmail.smtpserver.hook.RcptHook#doRcpt(com.googlecode.asyncmail.smtpserver.SMTPSession,
     *      org.apache.mailet.MailAddress, org.apache.mailet.MailAddress)
     */
    public HookResult doRcpt(SMTPSession session, MailAddress sender,
            MailAddress rcpt) {

        int rcptCount = 0;
        Collection<MailAddress> recipients = ((MailEnvelope) session.getState()
                .get(SMTPSession.MAIL_ENVELOPE)).getRecipients();
        if (recipients != null) {
            rcptCount = recipients.size();
        }
        rcptCount++;

        if (rcptCount > tarpitRcptCount) {
            if (session instanceof SMTPSessionImpl) {
                logger.debug("Add TarpitFilter to filterChain");
                ((SMTPSessionImpl) session).getIoSession().getFilterChain()
                        .addAfter("smtpResponseFilter",
                                TarpitFilter.TARPIT_FILTER, tFilter);
            }
        } else {
            logger.error("Class " + session.getClass().getName()
                    + " is not an instance of SMTPSessionImpl");
        }

        return new HookResult(HookReturnCode.DECLINED);
    }
}
